<!-- 留言评论模块 -->
<template>
  <div class="tmsgBox" ref="tmsgBox">
    <div class="tmsg-respond" ref="respondBox">
      <h3>发表评论 <small v-show="isRespond" class="tcolorm" @click="removeRespond">取消回复</small></h3>
      <form class="">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="说点什么呢.."
          v-model="textarea" />
        <el-row class="tmsg-r-info">
          <el-col :span="24" class="info-submit">
            <p class="tcolors-bg" @click="sendMsg">{{ sendTip }}</p>
          </el-col>
        </el-row>
      </form>
    </div>
    <div class="tmsg-comments" ref="listDom">
      <a href="#" class="tmsg-comments-tip">活捉
        {{ commentList.comment ? commentList.comment.length : 0 }} 条</a>
      <div class="tmsg-commentshow">
        <ul class="tmsg-commentlist">
          <li class="tmsg-c-item" v-for="(item,index) in commentList.comment" :key="'common'+index">
            <article class="">
              <header>
                <img :src="item.avatar" alt="" />
                <div class="i-name">
                  {{ item.username }}
                </div>
                <!-- <div class="i-class">
                    {{item.label}}
                </div> -->
                <div class="i-time">
                  <time>{{ item.createTime }}</time>
                </div>
              </header>
              <section>
                <p>{{ item.content }}</p>
                <div
                  v-if="hasLogin" class="tmsg-replay"
                  @click="respondMsg(item.id,item.id,item.createBy)">
                  回复
                </div>
                <el-input v-show="item.id===showId" v-model="textarea" placeholder="Please input">
                  <template #append>
                    <el-button @click="sendMsg">发布</el-button>
                  </template>
                </el-input>
              </section>
            </article>
            <ul
              v-show="item.children" class="tmsg-commentlist" style="padding-left:60px;">
              <li class="tmsg-c-item" v-for="(citem,cindex) in item.children" :key="'citem'+cindex">
                <article class="">
                  <header>
                    <img
                      :src="citem.avatar"
                      alt="" />
                    <div class="i-name">
                      {{ citem.username }} <span>回复</span> {{ citem.toCommentUsername }}
                    </div>
                    <div class="i-time">
                      <time>{{ citem.createTime }}</time>
                    </div>
                  </header>
                  <section>
                    <p>{{ citem.content }}</p>
                    <div
                      v-show="hasLogin" class="tmsg-replay"
                      @click="respondMsg(item.id,citem.id,citem.createBy)">
                      回复
                    </div>
                    <el-input
                      v-show="citem.id === showId" v-model="textarea"
                      placeholder="Please input">
                      <template #append>
                        <el-button @click="sendMsg">发布</el-button>
                      </template>
                    </el-input>
                  </section>
                </article>
              </li>
            </ul>
          </li>
        </ul>
        <h1 v-show="hasMore" class="tcolors-bg" @click="addMoreFun">查看更多</h1>
        <h1 v-show="!hasMore" class="tcolors-bg">没有更多</h1>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {commentApi} from "@/api/comment";
import {ElMessageBox} from "element-plus/es";
import {defineComponent, onMounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import localCache from "@/utils/localCache";
import {Comment} from "@/api/model/comment";

export default defineComponent({
  setup() {
    // id
    const showId = ref(0)
    const route = useRoute()
    const router = useRouter()
    const respondBox = ref<Node>()
    const listDom = ref<Node>()
    const tmsgBox = ref<HTMLElement | null>(null)
    const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      articleId: 0
    })
    const isRespond = ref(false)
    const textarea = ref('')
    let commentList = reactive(new Comment())
    const aid = ref(0)
    const hasMore = ref(false)
    const hasLogin = ref(false)
    const rootId = ref(-1)//根评论id，如果是针对文字评论直接用-1表示
    const toCommentId = ref(-1)//所回复评论的id
    const toCommentUserId = ref(-1)//所评论的用户id
    const sendTip = ref('发送~')
    const setData = (initData: any, result: any) => {
      const msg = result.rows;
      if (initData) {
        //刷新列表
        commentList.comment = msg;
      } else {
        //加载更多
        commentList.comment = commentList.comment.concat(msg);
      }
      hasMore.value = result.total > commentList.comment.length
    }

    //发送留言
    const sendMsg = async function () {//留言
      if (localCache.getCache('USER_INFO_')) {
        if (textarea.value) {
          sendTip.value = '咻~~';
          if (route.name === 'articleDetail') {
            await commentApi.sendArticleComment({
              id: aid.value,
              rootId: rootId.value,
              toCommentId: toCommentId.value,
              toCommentUserId: toCommentUserId.value,
              content: textarea.value
            }).then((response) => {
              console.log(response)
              textarea.value = '';
              rootId.value = -1;
              toCommentId.value = -1;
              toCommentUserId.value = -1;
              routeChange();
              removeRespond();
              const timer02 = setTimeout(function () {
                sendTip.value = '发送~';
                clearTimeout(timer02);
              }, 1000);
            })
          } else if (route.name === 'videoDetail') {
            await commentApi.sendVideoComment({
              id: aid.value,
              rootId: rootId.value,
              toCommentId: toCommentId.value,
              toCommentUserId: toCommentUserId.value,
              content: textarea.value
            }).then((response) => {
              console.log(response)
              textarea.value = '';
              rootId.value = -1;
              toCommentId.value = -1;
              toCommentUserId.value = -1;
              routeChange();
              removeRespond();
              const timer02 = setTimeout(function () {
                sendTip.value = '发送~';
                clearTimeout(timer02);
              }, 1000);
            })
          }

        } else {
          sendTip.value = '内容不能为空~'
          const timer = setTimeout(function () {
            sendTip.value = '发送~';
            clearTimeout(timer);
          }, 3000);
        }
      } else {
        ElMessageBox.confirm(
          '登录后即可点赞和收藏，是否前往登录页面?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
          }
        ).then(() => {
          //储存当前页面路径，登录成功后跳回来
          localStorage.setItem('logUrl', route.fullPath);
          router.push({path: '/Login?login=1'});
        }).catch(() => {

        })
      }

    }

    const respondMsg = function (rootId1: number, toCommentId1: number, toCommentUserId1: number) {//回复留言
      showId.value = toCommentId1
      // console.log(leavePid,pid);
      if (localCache.getCache('USER_INFO_')) {
        isRespond.value = true;
        rootId.value = rootId1
        toCommentId.value = toCommentId1;
        toCommentUserId.value = toCommentUserId1
      } else {
        ElMessageBox.confirm(
          '登录后即可点赞和收藏，是否前往登录页面?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
          }
        ).then(() => {
          //储存当前页面路径，登录成功后跳回来
          localStorage.setItem('logUrl', route.fullPath);
          router.push({path: '/Login?login=1'});
        }).catch(() => {

        })
      }
    }

    const removeRespond = function () {//取消回复留言
      isRespond.value = false;
      rootId.value = -1;
      toCommentId.value = -1;
      toCommentUserId.value = -1;
      tmsgBox.value?.insertBefore(respondBox.value as Node, listDom.value as Node);
    }

    const showCommentList = function (initData: any) {//评论列表
      aid.value = route.params.id == undefined ? 1 : parseInt(route.params.id as string);//获取传参的aid
      queryParams.articleId = aid.value
      //判断当前用户是否登录
      const token = localCache.getCache('token');
      hasLogin.value = !!token;

      if (route.name === 'articleDetail') {//文章列表的评论
        //公用设置数据方法
        commentApi.getArticleComment({
          id: queryParams.articleId,
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize
        }).then((response) => {
          const {data} = response.data
          setData(initData, data);
        }).catch(err => {
          console.log(err)
        })
      } else if (route.name === 'videoDetail') {//其他评论
        //公用设置数据方法
        commentApi.getVideoComment({
          id: queryParams.articleId,
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize
        }).then((response) => {
          const {data} = response.data
          setData(initData, data);
        }).catch(err => {
          console.log(err)
        })
      }


    }


    const addMoreFun = function () {//查看更多
      queryParams.pageNum++
      showCommentList(false);
    }

    const routeChange = function () {//重新加载
      queryParams.pageNum = 1
      showCommentList(true);
    }
    onMounted(() => {
      showCommentList(true)
    })
    return {
      respondBox,
      listDom,
      tmsgBox,
      queryParams,
      isRespond,
      textarea,
      commentList,
      aid,
      hasMore,
      hasLogin, showId,
      rootId,
      toCommentId,
      toCommentUserId,
      sendTip,
      setData,
      sendMsg,
      respondMsg,
      removeRespond,
      showCommentList,
      addMoreFun,
      routeChange
    }
  }
})


</script>

<style>
.tmsgBox {
  position: relative;
  background: #fff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 5px;
}

.tmsg-respond h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.tmsg-respond h3 small {
  font-size: smaller;
  cursor: pointer;
}

.tmsg-respond textarea {
  /*background: #f4f6f7;*/
  height: 100px;
  margin-bottom: 10px;
}


/*用户输入表单*/
.tmsg-r-info {
  margin: 10px 0;
}

.tmsg-r-info input {
  height: 30px;
  border-radius: 4px;
  background: #f4f6f7;
}

.tmsg-r-info .info-submit {
  margin: 10px 0;
  text-align: center;
}

.tmsg-r-info .info-submit p, .tmsg-commentshow h1 {
  /*background: #97dffd;*/
  /*color: #fff;*/
  border-radius: 5px;
  cursor: pointer;
  /*transition: all .3s ease-in-out;*/
  height: 30px;
  line-height: 30px;
  text-align: center;
}

/*.tmsg-r-info .info-submit p:hover{
    background: #47456d;
}*/
/*评论列表*/
.tmsg-comments .tmsg-comments-tip {
  display: block;
  border-left: 2px solid #363d4c;
  padding: 0 10px;
  margin: 40px 0;
  font-size: 20px;
}

.tmsg-commentlist {
  margin-bottom: 20px;

}

.tmsg-commentshow > .tmsg-commentlist {
  border-bottom: 1px solid #e5eaed;
}

.tmsg-c-item {
  border-top: 1px solid #e5eaed;
}

.tmsg-c-item article {
  margin: 20px 0;
}

.tmsg-c-item article header {
  margin-bottom: 10px;
}

.tmsg-c-item article header img {
  width: 65px;
  height: 65px;
  border-radius: 50%;
  float: left;
  transition: all .4s ease-in-out;
  -webkit-transition: all .4s ease-in-out;
  margin-right: 15px;
  object-fit: cover;
}

.tmsg-c-item article header img:hover {
  transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
}

.tmsg-c-item article header .i-name {
  font-size: 14px;
  margin: 5px 8px 7px 0;
  color: #444;
  font-weight: bold;
  display: inline-block;
}

.tmsg-c-item article header .i-class {
  display: inline-block;
  margin-left: 10px;
  background: #dff0d8;
  color: #3c763d;
  border-radius: 5px;
  padding: 3px 6px;
  font-size: 12px;
  font-weight: 400;
}

.tmsg-c-item article header .i-time {
  color: #aaa;
  font-size: 12px;
}

.tmsg-c-item article section {
  margin-left: 80px;
}

.tmsg-c-item article section p img {
  vertical-align: middle;
}

.tmsg-c-item article section .tmsg-replay {
  margin: 10px 0;
  font-size: 12px;
  color: #64609E;
  cursor: pointer;
}

</style>
